﻿using Coding4Fun.Lockscreen.Core.Models;
using Coding4Fun.Lockscreen.Mobile.Data;
using Microsoft.Phone.Controls;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Coding4Fun.Lockscreen.Mobile
{
    public partial class MainPage : PhoneApplicationPage
    {
        DataEngine dataEngine;

        public MainPage()
        {
            InitializeComponent();
            this.Loaded += MainPage_Loaded;
            dataEngine = new DataEngine();
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (CentralBindingPoint.Instance.Categories.Count == 0)
            {
                RefreshSetList();
            }

            LoadCustomCategories();
        }

        private void LoadCustomCategories()
        {
            try
            {
                CentralBindingPoint.Instance.CustomCategories = 
                    Coding4Fun.Toolkit.Storage.Serialize.Open<ObservableCollection<Category>>("customcat.xml");
            }
            catch
            {
                Debug.WriteLine("No customcat.xml - no registered custom categories.");
            }
        }

        async void RefreshSetList()
        {
            grdLoading.Visibility = System.Windows.Visibility.Visible;
            ApplicationBar.IsVisible = false;

            try
            {
                CentralBindingPoint.Instance.Categories = new ObservableCollection<Category>(await dataEngine.GetCategoryList());

                grdLoading.Visibility = System.Windows.Visibility.Collapsed;
                ApplicationBar.IsVisible = true;
            }
            catch
            {
                MessageBox.Show("There seems to be a problem getting the set list. Please try again later.",
                    "Download Wallpaper Sets", MessageBoxButton.OK);

                grdLoading.Visibility = System.Windows.Visibility.Collapsed;
                ApplicationBar.IsVisible = true;
            }
        }

        async void ListBox_SelectionChanged_1(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (lstWebCategories.SelectedItem != null)
            {
                Category selectedCategory = (Category)lstWebCategories.SelectedItem;

                try
                {
                    selectedCategory.Images = new ObservableCollection<Coding4Fun.Lockscreen.Core.Models.Image>
                        (await dataEngine.GetImagesByCategoryId((int)selectedCategory.id));

                    CentralBindingPoint.Instance.CurrentCategory = selectedCategory;


                    NavigationService.Navigate(new Uri("/ImageSetPage.xaml", UriKind.Relative));
                }
                catch
                {
                    MessageBox.Show("There seems to be a problem opening the category. Try again later.",
                                           "Open Category",
                                           MessageBoxButton.OK);
                }

                lstWebCategories.SelectedItem = null;
            }
        }

        private void btnAddCustomCategory_Click(object sender, EventArgs e)
        {
            TextBox textBox = new TextBox();

            CustomMessageBox box = new CustomMessageBox()
            {
                Caption = "Add Custom Category",
                Message = "Enter a unique name for the new category.",
                LeftButtonContent = "ok",
                RightButtonContent = "cancel",
                Content = textBox    
            };

            box.Dismissed += (s, boxEventArgs) =>
                {
                    switch (boxEventArgs.Result)
                    {
                        case CustomMessageBoxResult.LeftButton:
                            {
                                if (!string.IsNullOrWhiteSpace(textBox.Text))
                                {
                                    var categoryCheck = (from c in CentralBindingPoint.Instance.CustomCategories
                                                         where
                                                             c.Name == textBox.Text
                                                         select c).FirstOrDefault();

                                    if (categoryCheck == null)
                                    {
                                        Category category = new Category() { Name = textBox.Text };
                                        CentralBindingPoint.Instance.CustomCategories.Add(category);

                                        Coding4Fun.Toolkit.Storage.Serialize.Save<ObservableCollection<Category>>(
                                               "customcat.xml", CentralBindingPoint.Instance.CustomCategories);
                                    }
                                    else
                                    {
                                        MessageBox.Show("This category name was already taken!",
                                            "Add Custom Category",
                                            MessageBoxButton.OK);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Category name cannot be empty!",
                                           "Add Custom Category",
                                           MessageBoxButton.OK);
                                }
                                break;
                            };
                    }
                };

            box.Show();
        }

        private void lstCustomSets_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (lstCustomSets.SelectedItem != null)
            {
                Category selectedCategory = (Category)lstCustomSets.SelectedItem;
                CentralBindingPoint.Instance.CurrentCategory = selectedCategory;
                NavigationService.Navigate(new Uri("/ImageSetPage.xaml", UriKind.Relative));
            }

            lstCustomSets.SelectedItem = null;
        }

        private void btnRefreshSetList_Click_1(object sender, EventArgs e)
        {
            RefreshSetList();
        }

        private void btnDeleteSet_Click_1(object sender, RoutedEventArgs e)
        {
            Category category = (Category)((MenuItem)sender).Tag;

            if (MessageBox.Show("Are you sure you want to delete this category?", "Delete Category", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                CentralBindingPoint.Instance.CustomCategories.Remove(CentralBindingPoint.Instance.CustomCategories.Where(
                    x => x.Name == category.Name).First());

                Coding4Fun.Toolkit.Storage.Serialize.Save<ObservableCollection<Category>>(
                                               "customcat.xml", CentralBindingPoint.Instance.CustomCategories);
            }
        }
    }
}